package com.ruoyi.web.controller.system;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.system.domain.Card;
import com.ruoyi.system.service.ICardService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

@RestController
@RequestMapping("/system/card")
public class CardController extends BaseController {
    @Autowired
    private ICardService cardService;


    // 名片输出目录（从配置文件读取）
    @Value("${ruoyi.outputDir}")
    private String outputDir;

    // 模板地址
    @Value("${ruoyi.templatePath}")
    private String templatePath;

    // 生成名片
    @PostMapping("/generate")
    @Anonymous
    public ResponseEntity<?> generateBusinessCard(@RequestBody Map<String, String> requestData) {
        try {
            // 从请求数据中获取各个字段
            String avatar = requestData.getOrDefault("avatar", "未知");
            String name = requestData.getOrDefault("name", "未知");
            String title = requestData.getOrDefault("position", "职位未填");
            String company = requestData.getOrDefault("company", "公司未填");
            String phone = requestData.getOrDefault("phone", "手机号未填");
            String email = requestData.getOrDefault("email", "邮箱未填");
            String address = requestData.getOrDefault("address", "地址未填");

            // 确保输出目录存在
            File outputDirectory = new File(outputDir);
            if (!outputDirectory.exists()) {
                outputDirectory.mkdirs();
            }

            // 加载模板图片
            BufferedImage templateImage = ImageIO.read(new File(templatePath));

            // 创建 Graphics 对象
            Graphics2D graphics = templateImage.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            // 绘制内容到图片
            BufferedImage avatarImage = null;
            try {
                avatarImage = ImageIO.read(new URL(avatar));  // 读取头像图片
            } catch (IOException e) {
                e.printStackTrace();
                // 处理头像加载失败的情况
            }

            // 获取模板宽度（假设模板宽度是 600）
            int templateWidth = templateImage.getWidth();

            // 假设头像宽度是 200
            int avatarWidth = 200;

            // 计算头像的 X 坐标，使其位于右边
            int avatarX = templateWidth - avatarWidth - 50;  // 50 是距离右边的偏移量
            int avatarY = 50;  // Y 坐标不变

            if (avatarImage != null) {
                graphics.drawImage(avatarImage, avatarX, avatarY, avatarWidth, avatarWidth, null);
            }

            graphics.setFont(new Font("微软雅黑", Font.BOLD, 30));
            graphics.setColor(Color.BLACK);
            graphics.drawString(name, 100, 140);
            graphics.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            graphics.drawString(title, 420, 230);//职务
            graphics.drawString(company, 100, 230);//公司
            graphics.drawString(phone, 420, 140);
            graphics.drawString(email, 420, 320);
            graphics.drawString(address, 100, 320);

            // 释放资源
            graphics.dispose();

            // 保存图片到指定目录
            String outputFilePath = name + "_card.png";
            ImageIO.write(templateImage, "png", new File(outputDir + outputFilePath));

            // 构建返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("message", "名片生成成功");
            response.put("fileName", outputFilePath);

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("message", "名片生成失败");
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    // 新增名片
    @PostMapping
    public AjaxResult add(@RequestBody Card card) {
        return toAjax(cardService.insertCard(card));
    }

    // 根据姓名查询头像 TODO 未用到
    @GetMapping("/get-avatar-by-name")
    @Anonymous
    public AjaxResult getAvatarByName(@RequestParam String name) {
        // 根据姓名获取头像路径
        String avatarPath = cardService.getAvatarByName(name);

        // 返回头像路径
        return success(avatarPath);
    }

    // 根据用户ID查询信息
    @GetMapping("/user/{userId}")
    @Anonymous
    public AjaxResult getCardByUserId(@PathVariable("userId") Long userId) {
        // 调用服务层方法查询
        Card card = cardService.selectCardByUserId(userId);
        if (card == null) {
            return error("未找到对应的名片信息");
        }
        return success(card);
    }

    // 查询名片信息列表
    @GetMapping("/list")
    public TableDataInfo list(Card card) {
        startPage();
        List<Card> list = cardService.selectCardList(card);
        return getDataTable(list);
    }

    // 获取名片信息
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(cardService.selectCardById(id));
    }

    // 修改名片信息
    @PutMapping
    public AjaxResult edit(@RequestBody Card card) {
        return toAjax(cardService.updateCard(card));
    }

    // 删除名片信息
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(cardService.deleteCardByIds(ids));
    }
}
